<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>JavaScript Loan Calculator</title>
	
	<style type="text/css">
	
		.result
		{
			font-weight: bold;
		}
		
		#payment
		{
			text-decoration: underline;
		}
		
	</style>
	
</head>
<body>
	<form name="loandata">
		<table>
			<tr>
				<td><b>Enter Loan Information:</b></td>
			</tr>
			<tr>
				<td>1) Amount of the loan (any currency):</td>
				<td><input type="text" name="principal" onchange="calculate();"></td>
			</tr>
			<tr>
				<td>2) Annual percentage rate of interest:</td>
				<td><input type="text" name="interest" onchange="calculate();"></td>
			</tr>
			<tr>
				<td>3) Repayment period in years:</td>
				<td><input type="text" name="years" onchange="calculate();"></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="button" value="Compute" onclick="calculate();"></td>
			</tr>
			<tr><td><b>Payment Information:</b></td></tr>
			<tr>
				<td>4) Your monthly payment:</td>
				<td><span class="result" id="payment" /></td>
			</tr>
			<tr>
				<td>5) Your total payment:</td>
				<td><span class="result" id="total" /></td>
			</tr>
			<tr>
				<td>6) Your total interest payments:</td>
				<td><span class="result" id="totalinterest" /></td>
			</tr>
		</table>
	</form>

	<script type="text/javascript">
		/*
		 * This is the JavaScript function that makes the example work. Note that
		 * this script defines the calculate function called by the event
		 * handlers in the form. The functions reads values from de form
		 * <input> fields using the name fields int previous HTML code. It outputs
		 * its result into the named <span> elements 
		 */
		 
		 function calculate()
		 {
		 	var principal = document.loandata.principal.value;
		 	var interest = document.loandata.interest.value / 100 / 12;
		 	var payments = document.loandata.years.value * 12;
		 	
		 	// Now compute the monthly payment figure, using esoteric math
		 	var x = Math.pow(1 + interest, payments);
		 	var monthly = (principal * x * interest) / (x - 1);
		 	
		 	// Get named <span> elements from the form.
		 	var payment = document.getElementById("payment");
		 	var total = document.getElementById("total");
		 	var totalinterest = document.getElementById("totalinterest");
		 	
		 	// Check that the result is a finit number. If so, display the
		 	// results by setting the HTML content of each <span> element.
		 	if(isFinite(monthly))
		 	{
		 		payment.innerHTML = monthly.toFixed(2);
		 		total.innerHTML = (monthly * payments).toFixed(2);
		 		totalinterest.innerHTML = ((monthly * payments) - principal).toFixed(2);
		 	}
		 	else
		 	{
		 		payment.innerHTML = "";
		 		total.innerHTML = "";
		 		totalinterest.innerHTML = "";
		 	} 
		 }
	</script>

</body>
</html>